package com.zeny.online.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zeny.online.common.MsgActionEnum;
import com.zeny.online.common.OnlineException;
import com.zeny.online.common.OperatorFriendRequestTypeEnum;
import com.zeny.online.entity.FriendsRequest;
import com.zeny.online.entity.MyFriends;
import com.zeny.online.entity.Users;
import com.zeny.online.entity.vo.FriendRequestVO;
import com.zeny.online.mapper.FriendsRequestMapper;
import com.zeny.online.netty.DataContent;
import com.zeny.online.netty.UserChannelRel;
import com.zeny.online.service.FriendsRequestService;
import com.zeny.online.service.MyFriendsService;
import com.zeny.online.service.UsersService;
import com.zeny.online.util.JsonUtils;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class FriendsRequestServiceImpl extends ServiceImpl<FriendsRequestMapper, FriendsRequest> implements FriendsRequestService {


    @Autowired
    private MyFriendsService myFriendsService;

    @Autowired
    private UsersService usersService;

    /**
     * @param myUserId
     * @param friendUserId
     * @return void
     * @Description 根据自己的ID和想要添加好友的ID， 新增好友请求
     **/
    @Override
    public void addFriendRequest(String myUserId, String friendUserId) {
        //判断是不是正常用户
        Users me = usersService.getById(myUserId);
        Users friend = usersService.getById(friendUserId);
        if (me == null || friend == null) {
            throw new OnlineException(20002, "用户异常");
        }

        MyFriends myFriend = myFriendsService.findByMyUserIdAndFriendUserId(myUserId, friendUserId);
        if (myFriend != null) {
            //好友
            throw new OnlineException(20002, "已经是好友");
        }
        QueryWrapper<FriendsRequest> wrapper = new QueryWrapper<>();
        wrapper.eq("send_user_id", myUserId);
        wrapper.eq("accept_user_id", friendUserId);
        FriendsRequest friendsRequest = baseMapper.selectOne(wrapper);
        if (friendsRequest != null) {
            //已经申请过
            throw new OnlineException(20002, "已经申请过");
        }
        //添加好友请求
        friendsRequest = new FriendsRequest();
        friendsRequest.setSendUserId(myUserId);
        friendsRequest.setAcceptUserId(friendUserId);
        friendsRequest.setRequestDateTime(new Date());
        baseMapper.insert(friendsRequest);
    }

    /**
     * @param userId
     * @return java.util.List<com.zeny.online.entity.vo.FriendRequestVO>
     * @Description 好友请求列表
     **/
    @Override
    public List<FriendRequestVO> getUserListFromFriendRequest(String userId) {
        Users users = usersService.getById(userId);
        if (users == null) {
            throw new OnlineException(20002, "用户异常");
        }
        return baseMapper.getUserListFromFriendRequest(userId);
    }

    /**
     * @param sendUserId
     * @param acceptUserId
     * @param operType
     * @return void
     * @Description 处理好友请求
     **/
    @SuppressWarnings("all")
    @Transactional
    @Override
    public void operFriendRequest(String sendUserId, String acceptUserId, Integer operType) {
        //验证用户
        Users friend = usersService.getById(sendUserId);
        Users me = usersService.getById(acceptUserId);
        if (me == null || friend == null) {
            throw new OnlineException(20002, "用户异常");
        }

        synchronized (this) {
            if (OperatorFriendRequestTypeEnum.PASS.type.equals(operType)) {
                //判断是否是好友
                QueryWrapper<MyFriends> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("my_user_id", sendUserId);
                wrapper1.eq("my_friend_user_id", acceptUserId);
                MyFriends one = myFriendsService.getOne(wrapper1);
                if (one == null) {
                    //通过,同时更新好友列表
                    //站在当前用户角度看
                    MyFriends mf1 = new MyFriends();
                    mf1.setMyUserId(acceptUserId);
                    mf1.setMyFriendUserId(sendUserId);
                    //站在请求方用户角度看
                    MyFriends mf2 = new MyFriends();
                    mf2.setMyUserId(sendUserId);
                    mf2.setMyFriendUserId(acceptUserId);

                    myFriendsService.save(mf1);
                    myFriendsService.save(mf2);

                    //使用websocket主动推送消息到请求发起者，更新他的通讯录列表为最新
                    DataContent dataContent = new DataContent();
                    dataContent.setAction(MsgActionEnum.PULL_FRIEND.type);
                    Channel sendChannel = UserChannelRel.get(sendUserId);
                    if (sendChannel != null) {
                        sendChannel.writeAndFlush(new TextWebSocketFrame(JsonUtils.objectToJson(dataContent)));
                    }
                    Channel acceptChannel = UserChannelRel.get(acceptUserId);
                    if (acceptChannel != null) {
                        acceptChannel.writeAndFlush(new TextWebSocketFrame(JsonUtils.objectToJson(dataContent)));
                    }
                }
            }
        }

        //删除好友请求
        QueryWrapper<FriendsRequest> wrapper = new QueryWrapper<>();
        wrapper.eq("send_user_id", sendUserId);
        wrapper.eq("accept_user_id", acceptUserId);
        baseMapper.delete(wrapper);
    }
}
